package edg.db;

import java.sql.Statement;

public class User {
	
	/**
	 * Register a new user.
	 * @param name The user name.
	 * @param email The email address.
	 * @param password Plain text password (gets encrypted before being stored).
	 * @return Returns false if the user name is already taken or query fails
	 * for some other reason.  Returns true upon success.
	 */
	public static boolean register(String name, String password, String email) {		
		Database.sanitize(name);
		Database.sanitize(email);
		
		// TODO: detect strange characters from parameters, valid email, etc.
		
		Statement statement = Database.query(
				
				"INSERT " +
				"INTO users (name, password, email) " +
				"VALUES(" +
					"'" + name + "', " +
					"MD5('" + password + "'), " +
					"'" + email + "');"
					
			);
		
		// Unique index on name will cause the query to fail if the name already
		// exists, therefore making statement null.
		return statement != null;
	}
	
	/**
	 * Determine whether a particular name is available.
	 * @param name The name to be tested.
	 * @return Returns false if the name is not available, true otherwise.
	 */
	public static boolean isNameAvailable(String name) {
		Database.sanitize(name);
		
		Statement statement = Database.query(
				
				"SELECT * " +
				"FROM users " +
				"WHERE " +
					"name='" + name + "' " +
				"LIMIT 1;"
				
			);
		
		// The name is taken if a row is returned.
		try {			
			int count = 0;
			while(statement.getResultSet().next()) {
				count++;
			}
			if(count == 1) {
				return false;
			}
			else {
				return true;
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
	/**
	 * Determines whether a given name and password are valid.
	 * @param name The proposed name of the user.
	 * @param password The proposed password of the user.
	 * @return Returns true if the name and password are a valid combination,
	 * false otherwise.
	 */
	public static boolean login(String name, String password) {
		Database.sanitize(name);
		Database.sanitize(password);
		
		Statement statement = Database.query(
				
				"SELECT * " +
				"FROM users " +
				"WHERE " +
					"name='" + name + "' AND " +
					"password=MD5('" + password + "') " +
				"LIMIT 1;"
				
			);
		
		// The name and password are valid if a row is returned.
		try {			
			int count = 0;
			while(statement.getResultSet().next()) {
				count++;
			}
			if(count == 1) {
				return true;
			}
			else {
				return false;
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}
	
}